/*
 * author      : dormi330
 * date        : 2018/7/11
 * description : 订单TradeOrder工厂类
 */

package com.deep.trade.domain.order;

import com.deep.trade.common.TradeException;
import com.deep.trade.adaptor.required.IdService;
import com.deep.trade.adaptor.required.MemberAddress;
import com.deep.trade.adaptor.required.logistical.LogisticalService;
import com.deep.trade.adaptor.required.member.Member;
import com.deep.trade.adaptor.required.sku.ItemSkuService;
import com.deep.trade.adaptor.required.sku.Sku;
import com.deep.trade.order.dto.SkuAndQty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TradeOrderFactory {

    @Autowired
    private IdService idService;

    @Autowired
    private ItemSkuService itemSkuService;

    @Autowired
    private LogisticalService logisticalService;

    // ================== 新组装一个完整对象 ===================

    // 组装 TradeOrderSku 的数据
    List<TradeOrderSku> tradeOrderSku(List<SkuAndQty> skuAndQtyList, Member member, MemberAddress address) throws Exception {
        if (null == skuAndQtyList || skuAndQtyList.size() == 0) throw new TradeException("no sku presents");

        // 获取相关 SKU信息
        List<Sku> skuList = itemSkuService.skuOfIds(skuAndQtyList.stream()
                .map(SkuAndQty::getSkuId)
                .collect(Collectors.toList()));
        if (skuList.size() != skuAndQtyList.size()) throw new TradeException("some sku not exist");

        final Map<String, Sku> skuIdVsSku = new HashMap<>();
        skuList.forEach(sku -> skuIdVsSku.put(sku.getId(), sku));

        // 数据合法性检测
        for (SkuAndQty skuAndQty : skuAndQtyList) {
            if (skuAndQty.getQuantity() <= 0)
                throw new TradeException("item quantity illegal, quantity=" + skuAndQty.getQuantity());
            Sku skuFromItem = skuIdVsSku.get(skuAndQty.getSkuId());
            if (skuFromItem == null)
                throw new TradeException("item not exist, skuId=" + skuAndQty.getSkuId());
        }

        // 进行组装
        List<TradeOrderSku> tradeOrderSkuArrayList = new ArrayList<>(skuAndQtyList.size());
        for (SkuAndQty skuAndQty : skuAndQtyList) {
            Sku aSku = skuIdVsSku.get(skuAndQty.getSkuId());

            // 创建并初始化
            TradeOrderSku tradeOrderSku = new TradeOrderSku();
            BeanUtils.copyProperties(aSku, tradeOrderSku);
            tradeOrderSku.setSkuId(aSku.getId());

            tradeOrderSku.setCreatedBy(member.getId());
            tradeOrderSku.setUpdatedBy(member.getId());
            tradeOrderSku.setId(idService.uuid());
            tradeOrderSku.setQuantity(skuAndQty.getQuantity());

            // money & 计算相关钱
            tradeOrderSku.setPlatformDiscountMoney(BigDecimal.ZERO);
            tradeOrderSku.setShopDiscountMoney(BigDecimal.ZERO);
            tradeOrderSku.setSkuDiscountMoney(BigDecimal.ZERO);
            tradeOrderSku.setFreightMoney(freightOfEachSku(aSku.getId(), skuAndQty.getQuantity(), address));
            tradeOrderSku.calculateMoney();

            tradeOrderSkuArrayList.add(tradeOrderSku);
        }
        return tradeOrderSkuArrayList;
    }

    // 计算运费
    private BigDecimal freightOfEachSku(String skuId, int quanlity, MemberAddress address) throws Exception {
        return logisticalService.freightOfSku(skuId, quanlity, address);
    }

    //
    TradeOrder tradeOrderFromSku(TradeOrderSku tradeOrderSku, Member member, String remark) {
        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setId(idService.uuid());
        tradeOrder.setCreatedBy(member.getId());
        tradeOrder.setUpdatedBy(member.getId());

        // orderSummaryId   后面补充
        // orderType        暂不需要
        // orderChannel     暂不需要
        // code             暂不需要
        tradeOrder.setSellerId(tradeOrderSku.getSellerId());
        tradeOrder.setSellerName(tradeOrderSku.getSellerName());
        tradeOrder.setShopId(tradeOrderSku.getShopId());
        tradeOrder.setMemberId(member.getId());
        tradeOrder.setMemberName(member.getName());
        tradeOrder.setRemark(remark);
        // sellerRemark     暂不需要
        tradeOrder.setStatusEnum(OrderStatusEnum.TO_BE_AUDITED);
        tradeOrder.setSkuDiscountMoney(BigDecimal.ZERO);
        tradeOrder.setShopDiscountMoney(BigDecimal.ZERO);
        tradeOrder.setPlatformDiscountMoney(BigDecimal.ZERO);

        return tradeOrder;
    }

    // 创建一个 OrderSummary
    OrderSummary createOrderSummary(Member member) {
        OrderSummary orderSummary = new OrderSummary();
        orderSummary.setId(idService.uuid());
        orderSummary.setCreatedBy(member.getId());
        orderSummary.setUpdatedBy(member.getId());
        orderSummary.setMemberId(member.getId());
        orderSummary.setMemberName(member.getName());
        orderSummary.setPlatformDiscountMoney(platformDiscount());

        return orderSummary;
    }

    // 计算平台折扣, 这部分逻辑暂时没有
    private BigDecimal platformDiscount() {
        return BigDecimal.ZERO;
    }

    // 拆单之创建OrderDelivery
    DeliveryAddress deliveryAddressWithoutTradeOrderId(String memberId, MemberAddress address) {
        DeliveryAddress deliveryAddress = new DeliveryAddress();
        BeanUtils.copyProperties(address, deliveryAddress);
        deliveryAddress.setCreatedBy(memberId);
        deliveryAddress.setUpdatedBy(memberId);
        deliveryAddress.setId(idService.uuid());

        return deliveryAddress;
    }

}
